package kjj.android.bluetooth.app;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class BluetoothDeviceListActivity extends ListActivity {
	// Debugging
	private static final String TAG = "BluetoothDeviceListActivity";
	private static final boolean D = true;

	public static final String EXTRA_BTDEVICE_NAME = "bt_device_name";
	public static final String EXTRA_BTDEVICE_ADDRESS = "bt_device_address";

	private ArrayAdapter<String> mAllBtArrayAdapter;
	private ArrayList<String> mBtArrayList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (D)
			Log.v(TAG, "===onCreate===");

		setResult(RESULT_CANCELED);

		mBtArrayList = this.getIntent().getStringArrayListExtra(
				AndroidBluetoothActivity.EXTRA_DEVICE_LIST);

		mAllBtArrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, mBtArrayList);
		setListAdapter(mAllBtArrayAdapter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (D)
			Log.v(TAG, "===onDestroy===");
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		String btInfoString = ((TextView)v).getText().toString();
		String addr = btInfoString.substring(btInfoString.length() - 17);
		String nameString = btInfoString.substring(0, btInfoString.length() - 17);
		Intent intent = new Intent();
		intent.putExtra(EXTRA_BTDEVICE_ADDRESS, addr);
		intent.putExtra(EXTRA_BTDEVICE_NAME, nameString);
		setResult(RESULT_OK, intent);
		finish();
		
	}
}
